<template> 
  <el-card class="form-container" shadow="never">
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="填写商品信息"></el-step>
      <el-step title="填写商品促销"></el-step>
      <el-step title="填写商品属性"></el-step>
      <!-- <el-step title="选择商品关联"></el-step> -->
    </el-steps>
    <product-info-detail
      v-show="showStatus[0]"
      v-model="productParam"
      :is-edit="isEdit"
      @nextStep="nextStep">
    </product-info-detail>
    <product-sale-detail
      v-show="showStatus[1]"
      v-model="productParam"
      :is-edit="isEdit"
      @nextStep="nextStep"
      @prevStep="prevStep">
    </product-sale-detail>
    <product-attr-detail
      v-show="showStatus[2]"
      v-model="productParam"
      :is-edit="isEdit"
      @finishCommit="finishCommit"
      @prevStep="prevStep">
    </product-attr-detail>
    <!-- <product-relation-detail
      v-show="showStatus[3]"
      v-model="productParam"
      :is-edit="isEdit"
      @prevStep="prevStep"
      @finishCommit="finishCommit">
    </product-relation-detail> -->
  </el-card>
</template>
<script>
  import ProductInfoDetail from './ProductInfoDetail';
  import ProductSaleDetail from './ProductSaleDetail';
  import ProductAttrDetail from './ProductAttrDetail';
  import ProductRelationDetail from './ProductRelationDetail';
  import {createProduct,getProduct,updateProduct,fetchList as fetchProductList} from '@/api/product';
  import {fetchList as fetchDepotList} from '@/api/depository'

  const defaultProductParam = {
    albumPics: '',
    brandId: null,
    brandName: '',
    deleteStatus: 0,
    description: '',
    detailDesc: '',
    detailHtml: '',
    //detailMobileHtml: '',
    detailTitle: '',
    feightTemplateId: 0,
    flashPromotionCount: 0,
    flashPromotionId: 0,
    flashPromotionPrice: 0,
    flashPromotionSort: 0,
    giftPoint: 0,
    giftGrowth: 0,
    keywords: '',
    lowStock: 0,
    name: '',
    newStatus: 0,
    note: '',
    originalPrice: 0,
    pic: '',
    //会员价格{memberLevelId: 0,memberPrice: 0,memberLevelName: null}
    memberPriceList: [],
    //商品满减
    productFullReductionList: [{fullPrice: 0, reducePrice: 0}],
    //商品阶梯价格
    productLadderList: [{count: 0,discount: 0,price: 0}],
    previewStatus: 0,
    price: 0,
    price:0,//加元价格，现价
    originalPrice:0,//加元价格，市场价
    productAttributeCategoryId: null,
    productAttributeCategoryIdCopy:null,
    //商品属性相关{productAttributeId: 0, value: ''}
    productAttributeValueList: [],
    //商品sku库存信息{lowStock: 0, pic: '', price: 0, sale: 0, skuCode: '', sp1: '', sp2: '', sp3: '', stock: 0}
    skuStockList: [],
    //商品相关专题{subjectId: 0}
    subjectProductRelationList: [],
    //商品相关优选{prefrenceAreaId: 0}
    prefrenceAreaProductRelationList: [],
    productCategoryId: null,
    productCategoryName: '',
    productSn: '',
    promotionEndTime: '',
    promotionPerLimit: 0,
    promotionPrice: null,
    promotionStartTime: '',
    promotionType: 0,
    publishStatus: 0,
    recommandStatus: 0,
    sale: 0,
    serviceIds: '',
    sort: 0,
    stock: 0,
    subTitle: '',
    unit: '',
    usePointLimit: 0,
    verifyStatus: 0,
    weight: 0,
    depotList:[],//所有的仓库列表
    listTitle:"",//关联商品的标题
    relationProductIds:[],//关联商品id列表
    relationProducts:[],//关联商品列表
    productList:[],//商品列表
    answerAnduarantee:"",//答疑&保障
    showSale:0,//展示销量，zao假用的
    selectProductCateValue:[],//产品分类，有两级
    depotProductList:[],//spu的仓库id列表
    depotInfoForSku:[],//spu选择的仓库信息，在选择sku的时候使用；
    cateParentId:null,//商品分类的一级分类
   // tips:['','',''],
   tips:[],
  };
  const defaultListQuery = {
    keyword: null,
    pageNum: 1,
    pageSize: 10,
    publishStatus: 1,
    verifyStatus: 1,
    productSn: null,
    productCategoryId: null,
    brandId: null,
  };
  export default {
    name: 'ProductDetail',
    components: {ProductInfoDetail, ProductSaleDetail, ProductAttrDetail, ProductRelationDetail},
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        active: 0,
        productParam: Object.assign({}, defaultProductParam),
        showStatus: [true, false, false, false],
        listQuery: Object.assign({}, defaultListQuery),
      }
    },
    created(){
      console.log(this.productParam.tips)
      this.productParam.tips =[];
      // this.$set(this.productParam.tips,0,[])
      this.getDepotList();
      this.fetchProductList();
      if(this.isEdit){
        getProduct(this.$route.query.id).then(response=>{
          this.productParam = Object.assign(this.productParam,response.data);
          console.log("*&^%$%^&**productDetail********");
          let depotArr = response.data.depotProductList;
          this.productParam.tips= this.productParam.tips?this.productParam.tips.split(','):['','',''];
          this.productParam.depotInfoForSku = JSON.parse(JSON.stringify(depotArr));
          this.productParam.productAttributeCategoryIdCopy = this.productParam.productAttributeCategoryId;//备份一下
          let depotIds =[];
          depotArr.forEach(item =>{
            depotIds.push(item.depotId);
          });
          this.productParam.depotProductList = depotIds;
          console.log(this.productParam.depotProductList);
          //map不为空的话，把每个库存放到skuStockList中去
          let skuMap = this.productParam.productSkuDepotParamMap;
          if(JSON.stringify(skuMap) != "{}"){
            for(let item in skuMap){
              for(let item2 of this.productParam.skuStockList){
                if(item == item2.id && (!item2.depotParamList || item2.depotParamList.length==0)){
                  item2.depotParamList = skuMap[item]
                }
              }
            }
          }
         // this.productParam.selectProductCateValue = [4,45];
        //  this.productParam.selectProductCateValue.push(response.data.cateParentId);
        //  this.productParam.selectProductCateValue.push(response.data.productCategoryId);
        });
      };
    },
    methods: {
      getDepotList(){
        let self = this;
        fetchDepotList().then(res=>{
          if(res.code ==200 && res.data){
            self.productParam.depotList = res.data;
          }
        })
      },
      fetchProductList(){
        fetchProductList(this.listQuery).then(response => {
          //this.listLoading = false;
          this.productParam.productList = response.data.list;
          //this.total = response.data.total;
        });
      },
      hideAll() {
        for (let i = 0; i < this.showStatus.length; i++) {
          this.showStatus[i] = false;
        }
      },
      prevStep() {
        if (this.active > 0 && this.active < this.showStatus.length) {
          this.active--;
          this.hideAll();
          this.showStatus[this.active] = true;
        }
      },
      nextStep() {
        if (this.active < this.showStatus.length - 1) {
          this.active++;
          this.hideAll();
          this.showStatus[this.active] = true;
        }
      },
      finishCommit(isEdit) {
        console.log(JSON.parse(JSON.stringify(this.productParam.skuStockList)));
        console.log("提交")
        this.productParam.pic = this.productParam.pic == null? '':this.productParam.pic;
       console.log(this.productParam.pic)

        this.$confirm('是否要提交该产品', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // let depotIds = this.productParam.depotProductList;
          // let depotArr =[];
          // depotIds.forEach(item1=>{
          //   this.productParam.depotList.forEach(item2=>{
          //     if(item1 == item2.id){
          //       depotArr.push({
          //         depotId:item2.id,
          //         depotName:item2.name
          //       })
          //     }
          //   })
          // });
          
          // this.productParam.depotProductList = depotArr;
        /**
         * 因为get商品详情的接口里，skuStockList里的depotParamList是放在productSkuDepotParamMap字段中
         * 所以，如果用户进来什么都不操作，还是需要吧productSkuDepotParamMap字段里的数据放到skuStockList里的depotParamList中去
         * 但是呢，又要判断当前用户是不是已经操作过了，所以要对depotParamList进行判断
         * 
         */
//这个在刚进入页面的时候就去操作了
          // let skuMap = this.productParam.productSkuDepotParamMap;
          // if(JSON.stringify(skuMap) != "{}"){//map不为空的话，把每个库存放到skuStockList中去
          //   for(let item in skuMap){
          //     for(let item2 of this.productParam.skuStockList){
          //       if(item == item2.id && (!item2.depotParamList || item2.depotParamList.length==0)){
          //         item2.depotParamList = skuMap[item]
          //       }
          //     }
          //   }
          // }
          
        //   let tempstock=0;
          
        //   let tempdepotProductList =[];
        //   let skuInfo = this.productParam.skuStockList;
        //   for(const sku of skuInfo){
        //     let tempSkuStock =0;
        //     for(const item of sku.depotParamList){
        //       tempSkuStock+= parseInt(item.depotStock);
        //       sku.stock = tempSkuStock;
        //       tempstock +=  parseInt(item.depotStock);
        //       tempdepotProductList.push(item.depotId)
        //     }
        //   }
        //   tempdepotProductList = Array.from(new Set(tempdepotProductList));//目前sku来的仓库id列表
        //   console.log(tempdepotProductList);
        //   let tempDepotInfo =[];
        //   let depotList = this.productParam.depotList;
        //   for (const depot of tempdepotProductList){
        //       for(const item of depotList){
        //         if(depot == item.id){
        //           tempDepotInfo.push({
        //             depotId:item.id,
        //             depotName: item.name,
        //             productId: this.productParam.id
        //           })
        //         }
        //       }
        //   }
        //  console.log(tempDepotInfo);
        //   let depotArr = this.productParam.depotProductList;
        //   if(this.isEdit && depotArr && depotArr.length>0){
        //     let finalDepot =[];
        //     for(const dept of tempDepotInfo){
        //       for (const item of depotArr){
        //         if(dept.depotId == item.depotId){
        //           finalDepot.push({
        //             id:item.id,
        //             depotId:item.depotId,
        //             depotName:item.depotName,
        //           })
        //         }
        //       }
        //     }
        //     this.productParam.depotProductList = finalDepot;
        //   }
         
        //   this.productParam.depotProductList = tempDepotInfo;
        //   this.productParam.stock = tempstock;
          console.log("提交的sku信息：%￥￥&&&&&&&")
          // console.log(this.productParam.skuStockList);
           console.log(this.productParam.depotProductList);
           if(this.isEdit && this.productParam.depotProductList || this.productParam.depotProductList.length>0){
             delete this.productParam.depotProductList
           }
           console.log(this.productParam.depotProductList);
          //return
          //关联商品根据relationProducts，取出来id保存到relationProductIds
          if(this.productParam.relationProducts && this.productParam.relationProducts.length>0){
            let tempPIds=[];
            for (const pro of this.productParam.relationProducts){
              tempPIds.push(pro.id)
            }
            this.productParam.relationProductIds = tempPIds;
           // console.log(this.productParam.relationProductIds)
          }
          this.productParam.detailMobileHtml = this.productParam.detailHtml;
         
          this.productParam.price = this.productParam.price;
          this.productParam.originalPrice = this.productParam.originalPrice;
          //if(!this.isEdit){//新增
            if(this.productParam.skuStockList && this.productParam.skuStockList.length>0){
              let sku = this.productParam.skuStockList;
              sku.map(item=>{
                item.price = item.price
              })
            }
          //}
          console.log(this.productParam); 
          this.productParam.tips = this.productParam.tips && this.productParam.tips.length>1?this.productParam.tips.join(','):'';
          console.log(this.productParam.tips);
          console.log(this.productParam)
          //return
          if(isEdit){
            updateProduct(this.$route.query.id,this.productParam).then(response=>{
              this.$message({
                type: 'success',
                message: '提交成功',
                duration:1000
              });
              //this.$router.back();
              this.$router.push({path:'/pms/product',query:{pageNum:this.$route.query.pageNum}})
            });
          }else{
            createProduct(this.productParam).then(response=>{
              this.$message({
                type: 'success',
                message: '提交成功',
                duration:1000
              });
              this.$router.back();
            });
          }
        })
      }
    }
  }
</script>
<style>
  .app-main>.form-container {
    width: 1200px !important;
  }
</style>


